# -*- encoding: utf-8 -*-
from openerp.osv import fields,osv
import datetime
    
#只考虑两级BOM, 也不考虑单位换算的问题, 只适用于佛山北川    
class mrp_bom(osv.osv):
    _inherit = 'mrp.bom'

    def get_prods_cost(self, cr, uid, prod_ids, context=None):
        res = {}
        if not prod_ids:
            return res
        for prod_id in prod_ids:
            res[prod_id] = {'cost_material':0.0, 'cost_source':None}
        cr.execute('''
            select 
                a.product_id,
                case when c.price_stmt > 0 then c.price_stmt
                     when b.seller_price > 0 then b.seller_price
                     when a.standard_price > 0 then a.standard_price
                     else 0.0
                end as cost_price,
                case when c.price_stmt > 0 then 'purchase_cost'
                     when b.seller_price > 0 then 'supplier_cost'
                     when a.standard_price > 0 then 'product_cost'
                     else 'none'
                end as cost_source, 
                a.standard_price as standard_price, b.seller_price, c.price_stmt as purchase_price
            from (
                select a.id as product_id, b.standard_price 
                from product_product a
                join product_template b on a.product_tmpl_id = b.id
                ) as a
            left join (
                select c.id as product_id, a.seller_price
                from product_supplierinfo a
                join product_product c on a.id = c.seller_info_id
                ) as b on a.product_id = b.product_id
            left join (
                select a.product_id, a.price_order, a.price_stmt
                from stock_move a
                join (select a.product_id, max(a.date) as date
                    from stock_move a
                    join purchase_order_line b on a.purchase_line_id = b.id
                    where a.state='done'
                    and a.price_stmt > 0
                    and a.account_stmt_id is not null
                    group by a.product_id) as b on a.product_id = b.product_id and a.date = b.date
                ) as c  on a.product_id = c.product_id
            where a.product_id in %s
            ''',(tuple(prod_ids),))  
        for row in cr.fetchall():
            if row and row[0]:
                res[row[0]] = {'cost_material':row[1], 'cost_source':row[2]}
        return res
    
    #只是对于两级物料清单的计算
    def compute_cost(self, cr, uid, ids, context=None):
        for bom in self.browse(cr, uid, ids, context={'active_test':False}):
            self.compute_bom_cost(cr, uid, bom, context=context)
        return True
        
    def compute_bom_cost(self, cr, uid, bom, context=None):
        '''
                计算BOM的成本
        '''
        prod_obj = self.pool.get('product.product')
        cost_material_total = 0.0
        #计算部件的成本
        comp_prods = {}
        prod_ids = []
        for bom_line in bom.bom_lines:
            comp_prods[bom_line.product_id.id] = bom_line.id
            prod_ids.append(bom_line.product_id.id)
        prod_costs = self.get_prods_cost(cr, uid, prod_ids, context=context)
        for bom_line in bom.bom_lines:
            #johnw, 2017/02/15, 重新计算半成品成本的标志
            cost_material_unit = 0.0
            child_bom = None
            if bom_line.product_id.supply_method == 'produce':
                #找到子部件的BOM
                child_bom = prod_obj._prod_bom(cr, uid, bom_line.product_id, context=context)
            if not child_bom:
                prod_cost = prod_costs.get(bom_line.product_id.id)
                cost_source = prod_cost['cost_source'] != 'none' and prod_cost['cost_source'] or None
                cost_material_unit = prod_cost['cost_material']
            else:
                cost_source = 'child_total'
                cost_material_unit = self.compute_bom_cost(cr, uid, child_bom, context=context)
            cost_material = bom_line.product_qty * cost_material_unit
            self.write(cr, uid, [bom_line.id], {'cost_material': cost_material,
                                            'cost_source': cost_source,
#                                            'cost_work': 0.0,
                                            'cost_total': cost_material,
                                            'cost_compute_time':datetime.datetime.utcnow().strftime('%Y-%m-%d %H:%M:%S')}, context=context)
            cost_material_total += cost_material
        #成品的成本
        cost_work = bom.product_id.price_unit_workload * bom.product_id.mrp_workload
        self.write(cr, uid, bom.id, {'cost_material':cost_material_total, 
                                    'cost_source':'child_total',
#                                    'cost_work': cost_work,
                                    'cost_total':cost_material_total + cost_work,
                                    'cost_compute_time':datetime.datetime.utcnow().strftime('%Y-%m-%d %H:%M:%S')}, context=context)  
        return cost_material_total + cost_work    